package 栈;

import java.util.HashMap;
import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/valid-parentheses/
 */
public class _20_有效的括号 {
    /**
     * 一对一的关系  使用HashMap
     *
     * @param s
     * @return
     */
    public static HashMap<Character, Character> map = new HashMap<>();
    static {
        map.put('{', '}');
        map.put('[', ']');
        map.put('(', ')');
    }

    public boolean isValid(String s) {
    java.util.Stack<Character> stack = new Stack<>();
        int length = s.length();
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {
                stack.push(c);
            }else {
                if (stack.isEmpty()) return false;
                if (map.get(stack.pop())!=c){return false;}
            }
        }
        return stack.isEmpty();
    }

    /**
     * 利用栈先进后出的规则 实现括号匹配
     *
     * @param s
     * @return
     */
    public boolean isValid2(String s) {
    java.util.Stack<Character> stack = new Stack<>();
        int len = s.length();
        //{}()
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (c == '(' || c == '{' || c == '[') {//s 仅由括号 '()[]{}' 组成
                stack.push(c);
            } else { // 只剩下右括号
                if (stack.isEmpty()) return false;
                Character left = stack.pop();
                if (left == '(' && c != ')') return false;
                if (left == '{' && c != '}') return false;
                if (left == '[' && c != ']') return false;
            }
        }
        return stack.isEmpty();
    }


    /**
     * 替换字符串  效率低
     *
     * @param s
     * @return
     */
    public boolean isValid3(String s) {
        while (s.contains("{}") || s.contains("[]") || s.contains("()")) {
            s = s.replace("{}", "");
            s = s.replace("[]", "");
            s = s.replace("()", "");

        }
        return s.isEmpty();
    }
}
